#include "ScreenPresentation.h"
#include "ui_ScreenPresentation.h"
#include <QScrollBar>

ScreenPresentation::ScreenPresentation(QWidget *parent) :
	QWidget(parent),
	ui(new Ui::ScreenPresentation),
	_screenView(NULL)
{
	ui->setupUi(this);

	scene.setItemIndexMethod(QGraphicsScene::NoIndex);

	ui->graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
	ui->graphicsView->setScene(&scene);
	ui->graphicsView->setRenderHint(QPainter::Antialiasing);
	ui->graphicsView->setCacheMode(QGraphicsView::CacheBackground);
	ui->graphicsView->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate);
	ui->graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);
	//ui->graphicsView->viewport()->setCursor(Qt::ArrowCursor);
	//QApplication::setOverrideCursor( Qt::ArrowCursor );
	ui->graphicsView->setHorizontalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );
	ui->graphicsView->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );

	initScene();

	_ledsW = 10;
	_ledsH = 10;
}

ScreenPresentation::~ScreenPresentation()
{
	delete ui;
}

void ScreenPresentation::initScene(){
	// left
	for(int i=0;i<10;i++){
		LedView* led = new LedView(40,45 + i*10,40,180-40,80,this);
		led->setColor(QColor(qrand()%255,qrand()%255,qrand()%255));
		_ledsList.append(led);
		scene.addItem(led);
	}
	//
	for(int i=0;i<10;i++){
		LedView* led = new LedView(60 + i*10,45,40,90-40,80,this);
		led->setColor(QColor(qrand()%255,qrand()%255,qrand()%255));
		_ledsList.append(led);
		scene.addItem(led);
	}
	for(int i=0;i<10;i++){
		LedView* led = new LedView(180,45 + i*10,40,-40,80,this);
		led->setColor(QColor(qrand()%255,qrand()%255,qrand()%255));
		_ledsList.append(led);
		scene.addItem(led);
	}
	for(int i=0;i<10;i++){
		LedView* led = new LedView(60 + i*10,155,40,270-40,80,this);
		led->setColor(QColor(qrand()%255,qrand()%255,qrand()%255));
		_ledsList.append(led);
		scene.addItem(led);
	}

	_screenView = new ScreenView(0,0,100,50);
	scene.addItem(_screenView);
}

void ScreenPresentation::updateLeds(QRectF rect){
	int dx = rect.width()/_ledsW;
	int dy = rect.height()/_ledsH;

}

bool ScreenPresentation::addLeds(int xst, yst, bool CW){
	if(xst < 0 || xst >= _ledW || yst < 0 || xst >= _ledH){
		return false;
	}
	// remove leds
	for(int i=0;i<_ledsList.count();i++){
		scene.removeItem(_ledsList.at(0));
		delete _ledsList.at(0);
		_ledsList.erase(0);
	}

	int x = xst, y = yst;
	for(int i=0;i<_ledsH*_ledsW;i++){
		LedView* led = new LedView(0,0,40,0,80,this);
		_ledsList.apped(led);
		scene.addItem(led);

		//QPoint move(0,0);
		//if(x == _ledsW)
	}
}


void ScreenPresentation::resizeEvent(QResizeEvent * event){
	if(_screenView){
		_screenView->setGeometry(width(),height());
		QRectF rc = _screenView->boundingRect();
		updateLeds(rc);
		scene.setSceneRect(0,0,width(),height());
	}
}
